package org.mspring.mlog.web.module.admin;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mspring.mlog.entity.Album;
import org.mspring.mlog.entity.Photo;
import org.mspring.mlog.service.AlbumService;
import org.mspring.mlog.service.PhotoService;
import org.mspring.mlog.web.support.log.Log;
import org.mspring.platform.dao.Order.OrderType;
import org.mspring.platform.dao.Page;
import org.mspring.platform.dao.query.QueryBuilder;
import org.mspring.platform.utils.ValidatorUtils;
import org.mspring.platform.web.freemarker.widget.stereotype.Widget;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;

/**
 *
 * @author Gao Youbo
 * @since 2012-10-17
 */
@Widget
@RequestMapping("/admin/photo")
public class Admin_PhotoWidget extends Admin_AbstractWidget {

    @Autowired
    private PhotoService photoService;
    @Autowired
    private AlbumService albumService;
    @Autowired
    private MultipartResolver multipartResolver;

    @RequestMapping("/upload")
    public String photoUploadView(HttpServletRequest request, HttpServletResponse response, Model model) {
        List<Album> albums = albumService.listAll();
        model.addAttribute("albums", albums);
        return "/admin/photo/upload";
    }

    @RequestMapping("/doUpload")
    @ResponseBody
    @Log
    public String doUpload(@RequestParam(required = false) Long album, HttpServletRequest request, HttpServletResponse response) {
        MultipartFile image = getMultipartFile(request);
        if (album == null || image == null) {
            return "false";
        }
        try {
            long id = photoService.insert(image.getBytes(), album);
            Photo photo = photoService.get(id);
            return photo.getUrl();
        } catch (Exception e) {
            return "false";
        }
    }

    @RequestMapping("/list")
    @Log
    public String listPost(@ModelAttribute Page<Photo> photoPage, @ModelAttribute Photo photo, @RequestParam Map<String, Object> queryParams, HttpServletRequest request, HttpServletResponse response, Model model) {
        List<Album> albums = albumService.listAll();
        Long albumId = null;
        Album albumEntity = null;
        if (photo == null || photo.getAlbum() == null || photo.getAlbum().getId() == null) {
            Object obj = getSessionAttribute(request, "PhotoWidget_listPost_album");
            if (obj != null && ValidatorUtils.isInteger(obj.toString())) {
                albumId = new Long(obj.toString());
            }
        } else {
            albumId = photo.getAlbum().getId();
        }

        if (albumId == null) {
            albumEntity = albums.get(0);
            albumId = albumEntity.getId();
        } else {
            albumEntity = albumService.get(albumId);
        }
        setSessionAttribute(request, "PhotoWidget_listPost_album", albumId);

        if (photoPage == null) {
            photoPage = new Page<>();
        }
        photoPage.addOrder("id", OrderType.DESC);
        photoPage.setPageSize(21);
        QueryBuilder queryBuilder = QueryBuilder.instance(Photo.class, queryParams).buildValuedEqual("album.id", albumId);
        photoPage = photoService.listPage(queryBuilder, photoPage);
        model.addAttribute("album", albumEntity);
        model.addAttribute("albums", albums);
        model.addAttribute("photoPage", photoPage);
        return "/admin/photo/listPhoto";
    }

    @RequestMapping("/delete")
    @Log
    public String deletePhoto(@RequestParam(required = false) Long[] id, @ModelAttribute Page<Photo> photoPage, @ModelAttribute Photo photo, @RequestParam Map<String, Object> queryParams, HttpServletRequest request, HttpServletResponse response,
            Model model) {
        photoService.delete(id);
        return listPost(photoPage, photo, queryParams, request, response, model);
    }

    @RequestMapping("/edit")
    public String toEditPhoto(@RequestParam(required = false) Long id, @ModelAttribute Photo photo, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (id == null) {
            Object obj = getSessionAttribute(request, "PhotoWidget_edit_id");
            if (obj != null) {
                id = (Long) obj;
            }
        }
        if (id == null) {
            return prompt(model, "请先选择一张照片");
        }
        setSessionAttribute(request, "PhotoWidget_edit_id", id);

        photo = photoService.get(id);
        Album album = albumService.get(photo.getAlbum().getId());
        photo.setAlbum(album);
        model.addAttribute("photo", photo);
        model.addAttribute("album", album);
        return "/admin/photo/editPhoto";
    }

    @RequestMapping("/edit/save")
    @Log
    public String edit_save(@ModelAttribute Photo photo, HttpServletRequest request, HttpServletResponse response, Model model) {
        photoService.update(photo);
        return "redirect:/admin/photo/edit?id=" + photo.getId();
    }

    @RequestMapping("/cover")
    @ResponseBody
    @Log
    public String setCover(@RequestParam(required = false) Long albumId, @RequestParam(required = false) Long photoId, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (albumId == null || photoId == null) {
            return "false";
        }
        try {
            albumService.setCover(albumId, photoId);
        } catch (Exception e) {
            return "false";
        }
        return "true";
    }

    private MultipartFile getMultipartFile(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator(); it.hasNext();) {
            Map.Entry<String, MultipartFile> entity = it.next();
            return entity.getValue();
        }
        return null;
    }

}
